package com.whmnx.home.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.tencent.liteav.basic.log.TXCLog;
import com.tencent.qcloud.ugckit.UGCKitConstants;
import com.tencent.qcloud.ugckit.utils.LogReport;
import com.tencent.qcloud.ugckit.utils.TelephonyUtil;
import com.tencent.rtmp.ITXVodPlayListener;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.rtmp.TXLog;
import com.tencent.rtmp.TXVodPlayConfig;
import com.tencent.rtmp.TXVodPlayer;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.whmnx.base.bean.PlayerInfo;
import com.whmnx.base.bean.TCVideoInfo;
import com.whmnx.base.utils.TCTimeUtil;
import com.whmnx.base.view.TCPointSeekBar;
import com.whmnx.home.R;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import fr.castorflex.android.verticalviewpager.VerticalViewPager;
import io.reactivex.annotations.Nullable;
import me.goldze.mvvmhabit.utils.KLog;

public class TCVodPlayerActivity extends Activity implements  TelephonyUtil.OnTelephoneListener {
    private static final String TAG = "TCVodPlayerActivity";
    private VerticalViewPager mVerticalViewPager;
    private MyPagerAdapter mPagerAdapter;
    private TXCloudVideoView mTXCloudVideoView;
    private TextView mTvBack;
    private ImageView mIvCover;
    // 合拍相关
    private ImageButton mImgBtnFollowShot;
    // 发布者id 、视频地址、 发布者名称、 头像URL、 封面URL
    private List<TCVideoInfo> mTCLiveInfoList;
    private int mInitTCLiveInfoPosition;
    private int mCurrentPosition;

    /**
     * SDK播放器以及配置
     */
    private TXVodPlayer mTXVodPlayer;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);
        initDatas();
        initViews();
        initPlayerSDK();

        TelephonyUtil.getInstance().setOnTelephoneListener(this);
        TelephonyUtil.getInstance().initPhoneListener();

        //在这里停留，让列表界面卡住几百毫秒，给sdk一点预加载的时间，形成秒开的视觉效果
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void initDatas() {
        Intent intent = getIntent();
        mTCLiveInfoList = (List<TCVideoInfo>) intent.getSerializableExtra(UGCKitConstants.TCLIVE_INFO_LIST);
        mInitTCLiveInfoPosition = intent.getIntExtra(UGCKitConstants.TCLIVE_INFO_POSITION, 0);
    }

    private void initViews() {
        mTXCloudVideoView = (TXCloudVideoView) findViewById(R.id.player_cloud_view);
        mIvCover = (ImageView) findViewById(R.id.player_iv_cover);
        mTvBack = (TextView) findViewById(R.id.player_tv_back);
        mTvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mImgBtnFollowShot = (ImageButton) findViewById(R.id.imgBtn_follow_shot);
        mImgBtnFollowShot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 上报合唱
                LogReport.getInstance().reportChorus();
                // 合拍之前先下载视频

             /*   TCVideoInfo tcVideoInfo = mTCLiveInfoList.get(mCurrentPosition);
                FollowRecordDownloader downloader = new FollowRecordDownloader(TCVodPlayerActivity.this);
                downloader.setDuration(mTXVodPlayer.getDuration());
                downloader.downloadVideo(tcVideoInfo);*/
            }
        });
        mVerticalViewPager = (VerticalViewPager) findViewById(R.id.vertical_view_pager);
        mVerticalViewPager.setOffscreenPageLimit(2);
        mVerticalViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                TXLog.d(TAG, "mVerticalViewPager, onPageScrolled position = " + position);
            }

            @Override
            public void onPageSelected(int position) {
                TXLog.d(TAG, "mVerticalViewPager, onPageSelected position = " + position);
                mCurrentPosition = position;
                // 滑动界面，首先让之前的播放器暂停，并seek到0
                TXLog.d(TAG, "滑动后，让之前的播放器暂停，mTXVodPlayer = " + mTXVodPlayer);
                if (mTXVodPlayer != null) {
                    mTXVodPlayer.seek(0);
                    mTXVodPlayer.pause();
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        mVerticalViewPager.setPageTransformer(false, new ViewPager.PageTransformer() {
            @Override
            public void transformPage(View page, float position) {
                TXLog.d(TAG, "mVerticalViewPager, transformPage pisition = " + position + " mCurrentPosition" + mCurrentPosition);
                if (position != 0) {
                    return;
                }

                ViewGroup viewGroup = (ViewGroup) page;
                mIvCover = (ImageView) viewGroup.findViewById(R.id.player_iv_cover);
                mTXCloudVideoView = (TXCloudVideoView) viewGroup.findViewById(R.id.player_cloud_view);


                PlayerInfo playerInfo = mPagerAdapter.findPlayerInfo(mCurrentPosition);
                if (playerInfo != null) {
                    playerInfo.vodPlayer.resume();
                    mTXVodPlayer = playerInfo.vodPlayer;

                    playerInfo.vodPlayer.getDuration();
                    playerInfo.vodPlayer.getCurrentPlaybackTime();
                    float a = playerInfo.vodPlayer.getDuration() / playerInfo.vodPlayer.getCurrentPlaybackTime();
                    KLog.json("hhh",a + "");
                }
            }
        });

        mPagerAdapter = new MyPagerAdapter();
        mVerticalViewPager.setAdapter(mPagerAdapter);
    }



    class MyPagerAdapter extends PagerAdapter   {

        ArrayList<PlayerInfo> playerInfoList = new ArrayList<>();
        private int progress2;

        protected PlayerInfo instantiatePlayerInfo(int position) {
            TXCLog.d(TAG, "instantiatePlayerInfo " + position);

            PlayerInfo playerInfo = new PlayerInfo();
            TXVodPlayer vodPlayer = new TXVodPlayer(TCVodPlayerActivity.this);
            vodPlayer.setRenderRotation(TXLiveConstants.RENDER_ROTATION_PORTRAIT);
            //FIXBUG:FULL_SCREEN 合唱显示不全，ADJUST_RESOLUTION黑边
            vodPlayer.setRenderMode(0);


            TXVodPlayConfig config = new TXVodPlayConfig();

            //指定一个本地mp4缓存目录
            File sdcardDir = getExternalFilesDir(null);
            if (sdcardDir != null) {
                config.setCacheFolderPath(sdcardDir.getAbsolutePath() + "/txcache");
            }
            config.setMaxCacheItems(5);
            vodPlayer.setConfig(config);
            vodPlayer.setAutoPlay(false);

            TCVideoInfo tcLiveInfo = mTCLiveInfoList.get(position);
            playerInfo.playURL = TextUtils.isEmpty(tcLiveInfo.hlsPlayUrl) ? tcLiveInfo.playurl : tcLiveInfo.hlsPlayUrl;
            playerInfo.vodPlayer = vodPlayer;
            playerInfo.reviewstatus = tcLiveInfo.review_status;
            playerInfo.pos = position;
            playerInfoList.add(playerInfo);

            return playerInfo;
        }

        protected void destroyPlayerInfo(int position) {
            while (true) {
                PlayerInfo playerInfo = findPlayerInfo(position);
                if (playerInfo == null) {
                    break;
                }
                playerInfo.vodPlayer.stopPlay(true);
                playerInfoList.remove(playerInfo);

                TXCLog.d(TAG, "destroyPlayerInfo " + position);
            }
        }

        public PlayerInfo findPlayerInfo(int position) {
            for (int i = 0; i < playerInfoList.size(); i++) {
                PlayerInfo playerInfo = playerInfoList.get(i);
                if (playerInfo.pos == position) {
                    return playerInfo;
                }
            }
            return null;
        }

        public PlayerInfo findPlayerInfo(TXVodPlayer player) {
            for (int i = 0; i < playerInfoList.size(); i++) {
                PlayerInfo playerInfo = playerInfoList.get(i);
                if (playerInfo.vodPlayer == player) {
                    return playerInfo;
                }
            }
            return null;
        }

        public void onDestroy() {
            for (PlayerInfo playerInfo : playerInfoList) {
                playerInfo.vodPlayer.stopPlay(true);
            }
            playerInfoList.clear();
        }

        @Override
        public int getCount() {
            return mTCLiveInfoList.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            TXCLog.i(TAG, "MyPagerAdapter instantiateItem, position = " + position);
            TCVideoInfo videoInfo = mTCLiveInfoList.get(position);

            View view = LayoutInflater.from(container.getContext()).inflate(R.layout.view_player_content3, null);
            view.setId(position);

            // 封面
           /* ImageView coverImageView = (ImageView) view.findViewById(R.id.player_iv_cover);
            if (videoInfo.review_status == TCVideoInfo.REVIEW_STATUS_PORN) { //涉黄的图片不显示
                coverImageView.setImageResource(R.drawable.bg);
            } else {
                BitmapUtils.blurBgPic(TCVodPlayerActivity.this, coverImageView, videoInfo.frontcover, R.drawable.bg);
            }*/


          /*  TextView tvStatus = (TextView) view.findViewById(R.id.tx_video_review_status);
            if (videoInfo.review_status == TCVideoInfo.REVIEW_STATUS_NOT_REVIEW) {
                tvStatus.setVisibility(View.VISIBLE);
                tvStatus.setText(R.string.video_not_review);
            } else if (videoInfo.review_status == TCVideoInfo.REVIEW_STATUS_PORN) {
                tvStatus.setVisibility(View.VISIBLE);
                tvStatus.setText(R.string.video_porn);
            } else if (videoInfo.review_status == TCVideoInfo.REVIEW_STATUS_NORMAL) {
                tvStatus.setVisibility(View.GONE);
            }*/

            // 获取此player
            TXCloudVideoView playView = (TXCloudVideoView) view.findViewById(R.id.player_cloud_view);
            //进度条
            final TCPointSeekBar mSeekBarProgress = (TCPointSeekBar) view.findViewById(R.id.superplayer_seekbar_progress);

            final TextView  mTvCurrent = (TextView) view.findViewById(R.id.superplayer_tv_current);

            final TextView  mTvDuration = (TextView) view.findViewById(R.id.superplayer_tv_duration);

            RelativeLayout rl = (RelativeLayout) view.findViewById(R.id.rl);

            PlayerInfo playerInfo = instantiatePlayerInfo(position);
            playerInfo.playerView = playView;
            playerInfo.vodPlayer.setPlayerView(playView);

            playerInfo.vodPlayer.startPlay(playerInfo.playURL);

            if (playerInfo.vodPlayer.isPlaying()){
               // rl.setBackgroundResource(R.drawable.bar_back);
            }


            //监听播放
            playerInfo.vodPlayer.setVodListener(new ITXVodPlayListener() {
                @Override
                public void onPlayEvent(TXVodPlayer player, int event, Bundle param) {
                    if (event == TXLiveConstants.PLAY_EVT_CHANGE_RESOLUTION) {
                        int width = param.getInt(TXLiveConstants.EVT_PARAM1);
                        int height = param.getInt(TXLiveConstants.EVT_PARAM2);
                        //FIXBUG:不能修改为横屏，合唱会变为横向的
                    } else if (event == TXLiveConstants.PLAY_EVT_PLAY_END) {
                        restartPlay();
                    } else if (event == TXLiveConstants.PLAY_EVT_RCV_FIRST_I_FRAME) {// 视频I帧到达，开始播放
                        PlayerInfo playerInfo = mPagerAdapter.findPlayerInfo(player);
                        if (playerInfo != null) {
                            playerInfo.isBegin = true;
                        }
                        if (mTXVodPlayer == player) {
                            TXLog.i(TAG, "onPlayEvent, event I FRAME, player = " + player);
                            mIvCover.setVisibility(View.GONE);

                            LogReport.getInstance().reportVodPlaySucc(event);
                        }

                    } else if (event == TXLiveConstants.PLAY_EVT_VOD_PLAY_PREPARED) {
                        if (mTXVodPlayer == player) {
                            TXLog.i(TAG, "onPlayEvent, event prepared, player = " + player);
                            mTXVodPlayer.resume();
                        }

                    } else if (event == TXLiveConstants.PLAY_EVT_PLAY_BEGIN) { //开始播放
                        PlayerInfo playerInfo = mPagerAdapter.findPlayerInfo(player);
                        if (playerInfo != null && playerInfo.isBegin) {
                            mIvCover.setVisibility(View.GONE);
                            TXCLog.i(TAG, "onPlayEvent, event begin, cover remove");
                        }
                    } else if (event < 0) {
                        if (mTXVodPlayer == player) {
                            TXLog.i(TAG, "onPlayEvent, event prepared, player = " + player);

                            LogReport.getInstance().reportVodPlayFail(event);
                        }
                      // ToastUtil.toastShortMessage("event:" + event);
                    }else if (event == TXLiveConstants.PLAY_EVT_PLAY_PROGRESS){

                        int progress = param.getInt(TXLiveConstants.EVT_PLAY_PROGRESS_MS);
                        KLog.i(progress + "");
                        int duration = param.getInt(TXLiveConstants.EVT_PLAY_DURATION_MS);

                        mTvCurrent.setText(TCTimeUtil.formattedTime(progress));

                        mTvDuration.setText(TCTimeUtil.formattedTime(duration));


                        KLog.i(progress / 1000 + "----progress");
                        KLog.i(duration / 1000 + "----duration");

                        updateVideoProgress(progress / 1000, duration / 1000);
                        //总时长
                        // playerInfo.vodPlayer.getDuration();

                        //  playerInfo.vodPlayer.getCurrentPlaybackTime();

                        //  playerInfo.vodPlayer.getPlayableDuration();


                        //   KLog.i(playerInfo.vodPlayer.getCurrentPlaybackTime() + "----getCurrentPlaybackTime");
                        //    KLog.i(playerInfo.vodPlayer.getPlayableDuration() + "----getPlayableDuration");
                        //    KLog.i(playerInfo.vodPlayer.getDuration() + "----getDuration");

                        float percentage = (duration/1000) > 0 ? ((float) (progress/1000)  / (float) (duration/1000) ) : 1.0f;
                        int  progress2 = Math.round(percentage * mSeekBarProgress.getMax());

                        mSeekBarProgress.setProgress(progress2);




                        //   updateVideoProgress(playerInfo.vodPlayer.getPlayableDuration(), playerInfo.vodPlayer.getDuration());

                        // KLog.i(progress  / duration );
                    }
                }

                @Override
                public void onNetStatus(TXVodPlayer txVodPlayer, Bundle bundle) {

                }
            });

            playerInfo.vodPlayer.getDuration();
            playerInfo.vodPlayer.getCurrentPlaybackTime();
            float a = playerInfo.vodPlayer.getCurrentPlaybackTime() / playerInfo.vodPlayer.getDuration();
            KLog.json("hhh",a + "");





          //  playerInfo.vodPlayer.setVodListener(this);


           /* if (playerInfo.reviewstatus == TCVideoInfo.REVIEW_STATUS_NORMAL) {
            } else if (playerInfo.reviewstatus == TCVideoInfo.REVIEW_STATUS_NOT_REVIEW) { // 审核中
            } else if (playerInfo.reviewstatus == TCVideoInfo.REVIEW_STATUS_PORN) {       // 涉黄

            }*/
            container.addView(view);
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            TXCLog.i(TAG, "MyPagerAdapter destroyItem, position = " + position);

            destroyPlayerInfo(position);

            container.removeView((View) object);
        }
    }

    private void initPlayerSDK() {
        mVerticalViewPager.setCurrentItem(mInitTCLiveInfoPosition);
    }

    private void restartPlay() {
        if (mTXVodPlayer != null) {
            mTXVodPlayer.resume();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mTXCloudVideoView != null) {
            mTXCloudVideoView.onResume();
        }
        if (mTXVodPlayer != null) {
            mTXVodPlayer.resume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mTXCloudVideoView != null) {
            mTXCloudVideoView.onPause();
        }
        if (mTXVodPlayer != null) {
            mTXVodPlayer.pause();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTXCloudVideoView != null) {
            mTXCloudVideoView.onDestroy();
            mTXCloudVideoView = null;
        }

        mPagerAdapter.onDestroy();
        // true 代表清除最后一帧画面
        stopPlay(true);
        mTXVodPlayer = null;

        TelephonyUtil.getInstance().uninitPhoneListener();
    }

    protected void stopPlay(boolean clearLastFrame) {
        if (mTXVodPlayer != null) {
            mTXVodPlayer.stopPlay(clearLastFrame);
        }
    }




    private void updateVideoProgress(float mProgress, float mDuration) {
     //   mControllerWindow.updateVideoProgress(current, duration);


     //   KLog.i(percentage + "");

    }



    @Override
    public void onRinging() {
        if (mTXVodPlayer != null) {
            mTXVodPlayer.setMute(true);
        }
    }

    @Override
    public void onOffhook() {
        if (mTXVodPlayer != null) {
            mTXVodPlayer.setMute(true);
        }
    }

    @Override
    public void onIdle() {
        if (mTXVodPlayer != null) {
            mTXVodPlayer.setMute(false);
        }
    }

}
